package com.evosoft.vista.panel.usuarios;

import com.evosoft.enumeration.TipoEmpresaEnum;
import com.evosoft.excepciones.CantCreateUpdate;
import com.evosoft.excepciones.NotEntityFoundException;
import com.evosoft.facade.FacadeFactory;
import com.evosoft.linker.App;
import com.evosoft.model.Empresa;
import com.evosoft.model.Persona;
import com.evosoft.util.Sesion;
import com.evosoft.vista.dialog.CrearUsuario;
import com.evosoft.vista.panel.empresa.ListaEmpresa;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Silex RPR
 */
public class ListaUsuarios extends javax.swing.JPanel {

    /**
     * Creates new form ListaUsuarios
     */
    public ListaUsuarios() {
        initComponents();
        Persona personaEnSesion = Sesion.getInstance().getPersonaEnSesion();
        jLabel3.setText(personaEnSesion.getNombre() + " " + personaEnSesion.getApellido());
        if(personaEnSesion.getEmpresa().getTipo() != null)
           jLabel4.setText(personaEnSesion.getEmpresa().getNombre() + " ("+personaEnSesion.getEmpresa().getTipo().getNombre()+")");
        else
           jLabel4.setText(personaEnSesion.getEmpresa().getNombre() + " (Administrador de Sistema)");
        jLabel6.setText(personaEnSesion.getRol().getNombre());
        
        listaTable.setModel(model);
        listaTable.setColumnSelectionAllowed(false);
        listaTable.setRowSelectionAllowed(true);

        model.addColumn("Usuario");
        model.addColumn("Empresa");
        model.addColumn("Rol");
        
        listaTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        if(!personaEnSesion.getRol().getCreaUsuario()) {
            nuevoButton.setEnabled(false);
            jButton2.setEnabled(false);
            jButton1.setEnabled(false);
        }
        
        if(personaEnSesion.getEmpresa().getTipo() != null)
           if(personaEnSesion.getEmpresa().getTipo().getId() == TipoEmpresaEnum.PTOVENTA.getCodigo()) 
            nuevoButton.setEnabled(false);
        updateListModel();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        nuevoButton = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listaTable = new javax.swing.JTable();

        nuevoButton.setText("Nuevo");
        nuevoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nuevoButtonActionPerformed(evt);
            }
        });

        jButton2.setText("Eliminar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel1.setText("Nombre:");

        jLabel2.setText("Empresa:");

        jLabel3.setText("jLabel3");

        jLabel4.setText("jLabel4");

        jButton1.setText("Modificar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton3.setText("Detalles");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel5.setText("Rol:");

        jLabel6.setText("jLabel6");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel5))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(nuevoButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 102, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(19, 19, 19))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 20, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jLabel3)))
                    .addComponent(nuevoButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE)
                            .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6)))))
        );

        listaTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(listaTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 680, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void nuevoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoButtonActionPerformed
        CrearUsuario crearUsuario = new CrearUsuario(App.getInstance().getMainWindow(), true, null);
        crearUsuario.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosed(WindowEvent e) {
                }
        });
        
        crearUsuario.setLocationRelativeTo(null);
        crearUsuario.setVisible(true);
        
    }//GEN-LAST:event_nuevoButtonActionPerformed

    //Se usa para eliminar Usuarios
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        
        String usuarioSeleccionado = usuarioSeleccionado();
        if(usuarioSeleccionado.compareTo("") != 0) {
            try {
                int response = JOptionPane.showConfirmDialog(null, "Está seguro de eliminar este usuario?", "Confirmación",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                if (response == JOptionPane.YES_OPTION) {
                    Persona persona = FacadeFactory.getInstance().getPersonaFacade().obtenerPorUsuario(usuarioSeleccionado);
                    if(persona.getRol().getCreaEmpresa()) {
                        Empresa empresa = persona.getEmpresa();
                        empresa.setAdmin_id(0);
                        FacadeFactory.getInstance().getEmpresaFacade().actualizarEmpresa(empresa, Sesion.getInstance().getPersonaEnSesion().getId());
                    }
                    FacadeFactory.getInstance().getPersonaFacade().eliminarPersona(persona, Sesion.getInstance().getPersonaEnSesion().getId());
                    
                }
                
            }catch (NotEntityFoundException ex) {
                Logger.getLogger(ListaEmpresa.class.getName()).log(Level.SEVERE, null, ex);
            }catch (CantCreateUpdate ex) {
                JOptionPane.showMessageDialog(this, "Usted no posee permisos para realizar esta acción", "Error", JOptionPane.ERROR_MESSAGE);  
            }
            
            //Se usa para eliminar el tab de usuarios, volverlo a crear y de esta manera actualizarlo despues de eliminar usuarios
//            App.getInstance().getMainWindow().getAppTabPanel().remove(1);
//            App.getInstance().getMainWindow().getAppTabPanel().addTab("Usuarios", new ListaUsuarios());
            updateListModel();
        }
        
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        String usuario = usuarioSeleccionado();
        if(usuario.compareTo("") != 0) {
//            DetallesUsuarios detallesUsuarios = new DetallesUsuarios(usuario);
//            detallesUsuarios.setVisible(true);
            App.getInstance().getMainWindow().getAppTabPanel().setComponentAt(1, new DetallesUsuario(usuario));
        }        
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        String usuarioSeleccionado = usuarioSeleccionado();
        if(usuarioSeleccionado.compareTo("") != 0) {
            CrearUsuario crearUsuario = new CrearUsuario(App.getInstance().getMainWindow(), true,usuarioSeleccionado);
            crearUsuario.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosed(WindowEvent e) {
                }
        });
        
        crearUsuario.setLocationRelativeTo(null);
        crearUsuario.setVisible(true);
        }
        
    }//GEN-LAST:event_jButton1ActionPerformed

    public final void updateListModel() {
        
        if (model.getRowCount() > 0) {
            for (int i = model.getRowCount() - 1; i > -1; i--) {
                model.removeRow(i);
            }
        }
        
        List<Persona> lista = new ArrayList<Persona>();
        try {
            lista = FacadeFactory.getInstance().getPersonaFacade().obtenerPersonasDeAdmin(Sesion.getInstance().getPersonaEnSesion().getId());
        } catch (Exception ex) {
            Logger.getLogger(ListaEmpresa.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        Persona personaEnSesion = Sesion.getInstance().getPersonaEnSesion();
        if(personaEnSesion.getRol().getCreaEmpresa() && personaEnSesion.getEmpresa().getTipo() == null) {
            for(Persona p : lista) {
                if(p.getRol().getCreaEmpresa()) {
                    model.addRow(new Object[] {p.getUsuario(), p.getEmpresa().getNombre(), p.getRol().getNombre()});
                }
            }
        }else {
            for(Persona p : lista) {
                if((personaEnSesion.getRol().getId() >= 2 ) && p.getEmpresa().getId() == personaEnSesion.getEmpresa().getId())
                    model.addRow(new Object[] {p.getUsuario(), p.getEmpresa().getNombre(), p.getRol().getNombre()});
                else
                    model.addRow(new Object[] {p.getUsuario(), p.getEmpresa().getNombre(), p.getRol().getNombre()});
            }
        }
        
        listaTable.setModel(model);
    }
            
    private DefaultTableModel model = new DefaultTableModel() {
        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable listaTable;
    private javax.swing.JButton nuevoButton;
    // End of variables declaration//GEN-END:variables

    private String usuarioSeleccionado() {
        
        String usuario = "";
        if(listaTable.getSelectedRow() == -1) {
            JOptionPane.showMessageDialog(this, "NO seleccionó ningún dato", "Error", JOptionPane.ERROR_MESSAGE);
        }
        else {
            int fila = listaTable.getSelectedRow();
            //Se selecciona la columna 1 porque ahi esta el usuario, si se van a agregar mas columnas toca al final
            usuario = (String) listaTable.getModel().getValueAt(fila, 0);
        }
        return usuario;
    
    }
}
